package cn.com.project.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * JDK代理类 调用处理器
 */
public class JdkProxy implements InvocationHandler {

    private Object target ; // 需要代理的目标对象

    public JdkProxy(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("JDK动态代理，开始！");
        Object result = method.invoke(target, args);
        System.out.println("JDK动态代理，结束！");
        return result;
    }

    /**
     * 获取代理对象方法
     * @return
     */
    private Object getJDKProxy(){
        // JDK动态代理只能针对实现了接口的类进行代理，newProxyInstance 函数所需参数就可看出
        return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
    }

    public static void main(String[] args) {
        JdkProxy jdkProxy = new JdkProxy(new UserServiceImpl());
        // 获取代理对象
        UserService user = (UserService)jdkProxy.getJDKProxy();
        user.printUserName(1L); //执行方法
    }
}
